<?php

namespace App\Http\Middleware;

use App\Repositories\Permission\PermissionRepository;
use Closure;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminSessionIsValid
{
    public function handle(Request $request, Closure $next)
    {
        if (auth()->guard('admin')->guest()) {
            return redirect()->route('admin.login');
        }

        $admin = $request->user('admin');
//        $permissions = app(PermissionRepository::class)->getPermissions();
        $permissions = app(PermissionRepository::class)->getCachePermissions($admin->roles);
//        $permissions = [];
        Inertia::share([
            'auth' => [
                'id' => $admin->id,
                'name' => $admin->name,
                'phone' => $admin->phone,
                'role' => $admin->role,
                'avatar' => $admin->avatar,
            ],
            'permissions' => $permissions ?? [],
        ]);

        return $next($request);
    }
}
